<template>
  <div>
    <basic-container>
      <avue-crud :option="option"
        :table-loading="loading"
        :data="data"
        :page="page"
        ref="crud"
        v-model="form"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @on-load="onLoad"
      >
        <template slot="menuLeft">
          <el-button v-show="!isView" type="primary" size="small" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button v-show="isView" type="text" size="small" @click="handleSee(scope.row)">查看</el-button>
          <el-button v-show="!isView" type="text" size="small" @click="handleSet(scope.row)">编辑</el-button>
        </template>
      </avue-crud>
      <el-dialog
        title="因子"
        :visible.sync="dialogVisible"
        width="70%"
        :close-on-click-modal="false"
        :before-close="handleClose">
        <div>
          <el-tabs v-model="activeName" @tab-click="handleClickTab">
            <el-tab-pane label="基本信息" name="first">
              <el-form v-model="basicInfo" label-width="60px" :disabled="isView">
                <el-form-item label="名称： " prop="title">
                  <el-input v-model="basicInfo.title" placeholder="请输入因子名称"></el-input>
                </el-form-item>
                <el-form-item label="描述： " prop="desc">
                  <el-input type="textarea" rows="5" v-model="basicInfo.desc" placeholder="请输入描述"></el-input>
                </el-form-item>
                <el-form-item label="是否总纬度：" prop="isTotal" label-width="100px">
                  <el-radio-group v-model="basicInfo.isTotal">
                    <el-radio :label="true">是</el-radio>
                    <el-radio :label="false">否</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="排序：" prop="sort">
                  <el-input v-model.trim="basicInfo.sort" placeholder="请输入序号" type="number"></el-input>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <template v-if="addOreidt != 'add'">
              <el-tab-pane label="设置题目" name="second">
                <el-form v-model="topic" :disabled="isView">
                  <!-- <el-form-item label="规则：" prop="ruleId">
                    <el-select v-model="topic.ruleId">
                      <el-option v-for="rule in ruleList" :key="rule.id" :label="rule.name" :value="rule.id"></el-option>
                    </el-select>
                  </el-form-item> -->
                  <!-- <el-form-item label="题目编号：设置该维度对应的题目编号，用于维度分析与计分统计" prop="desc">
                    <br>
                    <label for="desc" style="font-size: 12px;">规则:({{ topicPh }})</label>
                    <el-input type="textarea" rows="7" v-model="topic.questIds" :placeholder="topicPh"></el-input>
                  </el-form-item> -->
                  <el-form-item label="计算公式：" prop="questIds">
                    <br>
                    <label for="questIds" style="font-size: 12px;">({{ topicPh }})</label>
                    <el-input type="textarea" rows="7" v-model="topic.questIds" :placeholder="topicPh"></el-input>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
              <el-tab-pane label="因子等级" name="third">
                <ScoreRule ref="scoreRule" :isView="isView" :templateId="templateId" :scaleId="rowId"></ScoreRule>
              </el-tab-pane>
            </template>
          </el-tabs>
        </div>
        <span style="position: absolute; right: 20px; top: 84px;" v-if="activeName != 'third' && !isView">
          <el-button size="small" type="primary" :loading="saveLoading" @click="onsave">保 存</el-button>
        </span>
      </el-dialog>
    </basic-container>
  </div>
</template>
<script>
import ScoreRule from './scoreRule'
import {
  getAnalyseList,
  addAnalyseDetail,
  deleteAnalyseDetail,
  getSelectRule
} from '@/api/platform/templateManage'
import { transformTopics } from '../utils'
export default {
  components: { ScoreRule },
  props: {
    templateId: {
      type: String,
      default: ''
    },
    isView: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      form: {},
      loading: true,
      selectionList: [],
      query: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      data: [],
      option: {
        height: 'auto',
        searchShow: true,
        searchMenuSpan: 6,
        tree: false,
        tip: false,
        border: true,
        index: true,
        selection: true,
        addBtn: false,
        menuWidth: 200,
        editBtn: false,
        viewBtn: false,
        column: [
          {
            label: "因子名称",
            prop: "title",
            search: false,
            rules: [
              {
                required: true,
                message: "请输入因子名称",
                trigger: "blur"
              }
            ]
          },
          {
            label: "描述",
            prop: "desc",
            search: false,
            rules: [
              {
                required: true,
                message: "请输入描述",
                trigger: "blur"
              }
            ]
          },
        ]
      },
      dialogVisible: false,
      activeName: 'first',
      basicInfo: {
        title: '',
        desc: '',
        isTotal: '',
        sort: 0
      },
      topic: {
        questIds: '',
        ruleId: ''
      },
      rowId: '',
      addOreidt: '',
      // 记录是否加载过计分规则
      isLoadRule: false,
      saveLoading: false,
      ruleList: [],
      // topicPh: `
      // 单独的题目编号用#连接，如果是连续的题目编号可用~，例如：
      // 第3、5、18题：3#5#18
      // 第1至46题：1~46
      // 第1至10和15~25题目：1~10#15~25
      // `
      topicPh: `
      规则：请输入您的计算公式，支持题目与分数的加减法。题目对应的分数用T+题号进行表示
      例如：
      1）第1~6题的总分，公式输入为：T1+T2+T3+T4+T5+T6
      2)  第1~6题的平均分，公式输入为：（T1+T2+T3+T4+T5+T6）/ 6
      3)  复杂的的公式例如：(T16-1)＋(T36-1)＋(T46-2) 表示第16题的分数减1分与第36题目的分数减1与第46题目的得分减2进行相加
      `
    }
  },
  watch: {
    isView: {
      handler(newVal) {
        this.option.delBtn = !newVal
      },
      immediate: true
    }
  },
  mounted() {
    this.getRule()
  },
  methods: {
    getRule() {
      getSelectRule().then(res => {
        this.ruleList = res.data.data
      })
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return deleteAnalyseDetail({ids: row.id});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      const d = {
        current: page.currentPage,
        size: page.pageSize,
        templateId: this.templateId,
        ...Object.assign(params, this.query)
      }
      getAnalyseList(d).then(res => {
        this.loading = false;
        this.page.total = res.data.data.total;
        this.data = res.data.data.records;
      })
    },
    handleAdd() {
      this.dialogVisible = true
      this.addOreidt = 'add'
    },
    handleSee(row){
      this.dialogVisible = true
      this.addOreidt = 'view'
      this.basicInfo.title = row.title
      this.basicInfo.desc = row.desc
      this.basicInfo.isTotal = row.isTotal
      this.basicInfo.sort = row.sort
      this.topic.ruleId = row.ruleId == 0 ? '' : Number(row.ruleId)
      // this.topic.questIds = row.questIds.replace(/,/g, '\n')
      this.rowId = row.id
      // this.topic.questIds = transformTopics()[1](row.questIds)
      this.topic.questIds = row.questIds
    },
    handleSet(row) {
      this.dialogVisible = true
      this.addOreidt = 'edit'
      this.basicInfo.title = row.title
      this.basicInfo.desc = row.desc
      this.basicInfo.isTotal = row.isTotal
      this.basicInfo.sort = row.sort
      this.topic.ruleId = row.ruleId == 0 ? '' : Number(row.ruleId)
      // this.topic.questIds = row.questIds.replace(/,/g, '\n')
      this.rowId = row.id
      // this.topic.questIds = transformTopics()[1](row.questIds)
      this.topic.questIds = row.questIds
    },
    handleClickTab(active) {
      if (active.name == 'third' && !this.isLoadRule) {
        this.$nextTick(() => {
          this.$refs.scoreRule.onLoad(this.$refs.scoreRule.page)
          this.isLoadRule = true
        })
      }
     },
    handleClose() {
      this.dialogVisible = false;
      this.basicInfo = {
        title: '',
        desc: '',
        isTotal: '',
        sort: 0
      }
      this.topic = { questIds: '', ruleId: '' }
      this.rowId = ''
      this.activeName = 'first'
      this.addOreidt = 'add'
      this.isLoadRule = false
      this.onLoad(this.page)
    },
    onsave() {
      let d = {
        templateId: this.templateId,
        title: this.basicInfo.title,
        desc: this.basicInfo.desc,
        isTotal: this.basicInfo.isTotal,
        // ruleId: this.topic.ruleId || 0, 改成直接输入计算工时不需要此字段了
        sort: this.basicInfo.sort,
        // questIds: this.topic.questIds.replace(/\n/g, ',')
        // questIds: transformTopics()[0](this.topic.questIds)
        questIds: this.topic.questIds
      }
      this.rowId ? (d.id = this.rowId) : ''
      this.saveLoading = true
      addAnalyseDetail(d).then(res => {
        const r = res.data
        if (r.code == 200) {
          this.$message.success(r.msg || '成功')
        }
      }).finally(() => {
        if(this.addOreidt == 'add') this.handleClose()
        setTimeout(() => {
          this.saveLoading = false
        }, 500);
      })
    }
  }
}
</script>
